﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace NeuralStock.Tools
{
    public static class CsvExporter
    {
        public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)
        {
            Type t = typeof(T);
            PropertyInfo[] properties = t.GetProperties();

            string header = String.Join(separator, properties.Select(p => p.Name).ToArray());

            StringBuilder csvdata = new StringBuilder();
            csvdata.AppendLine(header);

            foreach (var o in objectlist)
            {
                csvdata.AppendLine(ToCsvFields(separator, properties, o));
            }

            return csvdata.ToString();
        }

        public static string ToCsvFields(string separator, PropertyInfo[] properties, object o)
        {
            StringBuilder line = new StringBuilder();

            foreach (var p in properties)
            {
                if (line.Length > 0)
                    line.Append(separator);

                var x = p.GetValue(o, null);

                if (x != null)
                {
                    line.Append(x.ToString());
                }
                else
                {
                    line.Append(" ");
                }
            }

            return line.ToString();
        }
    }
}
